﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharePointOptimizer.Model;
using SharePointOptimizer.BL.DataAnalysis;
using AG.Utilities;

namespace SharePointOptimizer.BL.DataAnalysis.IssueTypes
{
    public class ServerCheckFreeSpaceLess10percent : IssueTypeCheckBase
    {

        public ServerCheckFreeSpaceLess10percent(int issueTypeId)
            : base(issueTypeId)
        {

        }

        public override void Check()
        {
            try
            {
                SharePointOptimizerDataContext dc = new SharePointOptimizerDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
                Issue issue;
                Farm farm = dc.Farms.FirstOrDefault();


                if (farm != null)
                {

                    Service service = farm.Services.SingleOrDefault(s => s.TypeName == "Microsoft SharePoint Foundation Web Application");


                    if (service != null)
                    {
                        var ServerQry = from sd in dc.Servers
                                        from d in sd.Disks

                                        where d.ServerID == sd.ServerID
                                        where
                                         (Convert.ToDouble(((d.Size - d.Used) / d.Size)) < issueType.ThresholdValue/100)


                                        select d;

                        foreach (var item in ServerQry)
                        {

                            //Get Issuetype object

                            //Get Issuetype object  And Create a new  Global issue object 

                            IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                            issue = new Issue();

                            issue.IssueType = issueType;
                            issue.TargetId = item.ServerID;
                            issue.Description = issueType.Description.Replace("{serverName}", item.Server.Name);
                            issue.Description = issue.Description.Replace("{diskname}", item.Name);
                            issue.Description = issue.Description.Replace("{minFreeSpace}", issueType.ThresholdValue.ToString());

                            dc.Issues.InsertOnSubmit(issue);
                        }

                        dc.SubmitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }








    }

}